package oh.june.keepscreenonwatch;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import android.app.Activity;
import android.app.Dialog;
import android.content.Intent;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.provider.Settings.Global;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.LinearLayout.LayoutParams;
import android.widget.ListView;
import android.widget.TextView;

public class MainActivity extends Activity {
	
	private AppListAdapter _adapter;
	private PackageManager _pm;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		PrefUtil.initialize(this);
		
		// Creates the layout for the window and the look of it
        requestWindowFeature(Window.FEATURE_ACTION_BAR);
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND,
                WindowManager.LayoutParams.FLAG_DIM_BEHIND);
        
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
        
        // Params for the window.
        // You can easily set the alpha and the dim behind the window from here
        WindowManager.LayoutParams params = getWindow().getAttributes();
        params.alpha = 3.0f;    // lower than one makes it more transparent
        params.dimAmount = 0f;  // set it higher if you want to dim behind the window
        getWindow().setAttributes(params);
        
        setContentView(R.layout.activity_main);
        
        _pm = getPackageManager();
        
        RoundButton btnAdd = (RoundButton)findViewById(R.id.btn_add);
        btnAdd.setStyle(RoundButton.TYPE_YELLOW);
        btnAdd.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				showApplicationListPopup();
			}
		});
        
        RoundButton btnOffScreen = (RoundButton)findViewById(R.id.btn_offscreen);
        btnOffScreen.setStyle(RoundButton.TYPE_YELLOW);
        btnOffScreen.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				startActivity(new Intent(MainActivity.this, OffScreenActivity.class));
			}
		});
        
        ListView appList = (ListView)findViewById(R.id.app_list);
        appList.setOnItemClickListener(new OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
				ApplicationInfo info = _adapter.getItem(position);
				try{
					Intent startIntent =_pm.getLaunchIntentForPackage(info.packageName);
					startActivity(startIntent);
				}catch(Exception e){
					e.printStackTrace();
				}
			}
		});
        _adapter = new AppListAdapter(this, _pm);
        appList.setAdapter(_adapter);
        
        initSavedState();
	}

	private void initSavedState() {
		String str = PrefUtil.get("SAVED_LIST", "");
		String[] strList = str.split("\\^");
		ArrayList<ApplicationInfo> info = new ArrayList<ApplicationInfo>();
		
		List<String> packages = Arrays.asList(strList);
		for(int i=0; i<packages.size(); i++){
			String packageName = packages.get(i);
			try{
				ApplicationInfo item = _pm.getApplicationInfo(packageName, 0);
				info.add(item);
			}catch(Exception e){
				e.printStackTrace();
			}
		}
		
		Log.i("TEST", strList.toString());		
		_adapter.addAll(info);	
	}

	protected void showApplicationListPopup() {
		
		List<ApplicationInfo> wholepackages = _pm.getInstalledApplications(PackageManager.GET_META_DATA);
		ArrayList<ApplicationInfo> packages = new ArrayList<ApplicationInfo>();
		
		for(ApplicationInfo info : wholepackages){
			if(!((info.flags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) == 1)) {
				packages.add(info);
			}
		}
		
		final Dialog menuDialog = new Dialog(this, R.style.Theme_CustomDialog_NoBackground);
		menuDialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
		menuDialog.setContentView(R.layout.dialog_applist);
		menuDialog.setCancelable(false);
		
		RoundButton closeBtn = (RoundButton) menuDialog.findViewById(R.id.btn_close);
		RoundButton saveBtn = (RoundButton) menuDialog.findViewById(R.id.btn_save);
		closeBtn.setStyle(RoundButton.TYPE_YELLOW);
		saveBtn.setStyle(RoundButton.TYPE_YELLOW);
		
		ListView list = (ListView) menuDialog.findViewById(R.id.list_applist);
		final ApplicationListAdapter adapter = new ApplicationListAdapter(this, _pm);
		list.setAdapter(adapter);
		
		adapter.addAll(packages);
		adapter.notifyDataSetChanged();
		
		closeBtn.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				menuDialog.dismiss();
			}
		});
		
		saveBtn.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				saveCheckedList(adapter);
				menuDialog.dismiss();
			}
		});
		menuDialog.show();
	}

	protected void saveCheckedList(ApplicationListAdapter adapter) {
		ArrayList<ApplicationInfo> list = adapter.getCheckedInfoList();
		_adapter.clear();
		_adapter.addAll(list);
		_adapter.notifyDataSetChanged();
		
		StringBuilder builder = new StringBuilder();
		//for(ApplicationInfo info : list){
		for(int i=0; i<list.size(); i++){
			ApplicationInfo info = list.get(i);
			builder.append(info.packageName);
			if(i != list.size()-1){
				builder.append("^");	
			}
		}
		PrefUtil.set("SAVED_LIST", builder.toString());
		
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		getMenuInflater().inflate(R.menu.main, menu);
		return true;
	}

}
